﻿using HtmlAgilityPack;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using YouWei.Infrastructure.Entity;
using YouWei.Infrastructure.Models;
using YouWei.Infrastructure.Service;
using YouWei.Utility;

namespace ArticleCrawling
{
    public class BbsScraping
    {
        private string BaseUrl = "http://bbs.cheshi.com/";

        public void Excute()
        {
            //var list = GetCommentList("");

            // var dto = GetCircleToComent(list.First());
            //var entity = new GroupComment()
            //{
            //    IsActvie = 1,
            //    CreateDate = DateTime.Now,
            //    IsHot = 0,
            //    CommentDesc = dto.CommentName,
            //    CommentName = dto.CommentName
            //};
            ////评论和浏览量随机人数
            //entity.PageViews = entity.PageViews < 50 ? new Random().Next(50, 300) : entity.PageViews;
            //entity.PraiseCount = entity.PraiseCount < 50 ? new Random().Next(50, 300) : entity.PraiseCount;

            //var groupCommentID = Convert.ToInt32(new GroupCommentService().Insert(entity));
            //var detailEntity = new GroupCommentDetail()
            //{
            //    CreateDate = DateTime.Now,
            //    Detail = dto.Detail,
            //    GroupCommentID = groupCommentID
            //};

        }

        /// <summary>
        /// 返回模块的文章链接列表
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public List<string> GetCommentList(string content)
        {
            var list = new List<string>();
            //var TextListUrl = "/forum-news-1449-1.html";
            ////IHtmlDocument source = new JumonyParser().LoadDocument(TextListUrl, System.Text.Encoding.GetEncoding("utf-8"));
            //RestClient client = new RestClient(TextSite);

            ////var request = new RestRequest("/2/short_url/shorten.json?source=2849184197&url_long=" + HttpUtility.UrlEncode(linkurl), Method.GET);
            //var request = new RestRequest(TextListUrl, Method.GET);
            //IRestResponse response = client.Execute(request);
            //var content = response.Content;
            var htmlDoc = new HtmlDocument();
            htmlDoc.LoadHtml(content);
            var sq_circleList = htmlDoc.DocumentNode.SelectNodes("//div[@class='sq_circleList']/h3/a");
            //HtmlDocument source = new JumonyParser().Parse(content);
            //圈子内容
            //var sqContent = source.Find(".sq_content");
            //if (sqContent == null || sqContent.Count() < 1)
            //    return list;
            ////圈子内容里的文章列表
            //var sq_circleList = sqContent.Find(".sq_circleList");
            if (sq_circleList == null || sq_circleList.Count < 1)
                return list;

            foreach (var item in sq_circleList)
            {
                string href = item.GetAttributeValue("href", "");
                if (!string.IsNullOrEmpty(href))
                {
                    if (!href.StartsWith("http"))
                    {
                        href = BaseUrl + href;
                    }
                    list.Add(href);
                }
            }
            //var aDoms = sq_circleList.Find("h3 a");
            //var aDoms = sq_circleList.Find("h3 a");
            //if (aDoms == null || aDoms.Count() < 1)
            //    return list;

            //foreach (var a in aDoms)
            //{
            //    var href = a.Attribute("href");
            //    var strHref = href.AttributeValue;
            //    if (!string.IsNullOrWhiteSpace(strHref))
            //        list.Add(strHref);
            //}
            return list;
        }


        /// <summary>
        /// 解析文章详情
        /// </summary>
        /// <param name="href"></param>
        /// <returns></returns>
        public void GetCircleToComent(string content)
        {
            var entity = new GroupCommentDto() { CreateDate = DateTime.Now };
            //var TextListUrl = href;
            //RestClient client = new RestClient(TextSite);
            //var request = new RestRequest(TextListUrl, Method.GET);
            //IRestResponse response = client.Execute(request);
            //var content = response.Content;
            //IHtmlDocument source = new JumonyParser().Parse(content);
            var htmlDoc = new HtmlDocument();
            htmlDoc.LoadHtml(content);
            var sq_des = htmlDoc.DocumentNode.SelectNodes("//div[@class='sq_des']");
            //var sq_des = source.Find(".sq_des");
            if (sq_des == null || sq_des.Count < 1)
                return ;
            var title = sq_des[0].SelectNodes(".//h3[@class='title']");
            if (title == null || title.Count < 1)
                return ;
            entity.CommentName = title.First().InnerText.Trim();
            // var info = sq_des.Find(".sq_des_info");
            var info = sq_des[0].SelectNodes(".//div[@class='sq_des_info']");
            if (info == null || info.Count < 1)
                return ;

            var process = new CommentDetailProcess();
            entity.Detail = process.ProcessDetail(info.First().InnerHtml);
            
            entity.IsActvie = 1;
            entity.CreateDate = DateTime.Now;
            entity.IsHot = 0;

            //评论和浏览量随机人数
            entity.PageViews = entity.PageViews < 50 ? new Random().Next(50, 300) : entity.PageViews;
            entity.PraiseCount = entity.PraiseCount < 50 ? new Random().Next(50, 300) : entity.PraiseCount;

            var groupCommentID = Convert.ToInt32(new GroupCommentService().Insert(entity));
            var detailEntity = new GroupCommentDetail()
            {
                CreateDate = DateTime.Now,
                Detail = entity.Detail,
                GroupCommentID = groupCommentID
            };
        }
    }
}
